package com.wechat.url.controller;

import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.wechat.url.common.Const;
import com.wechat.url.common.JsonConst;
import com.wechat.url.common.model.Url;
import com.wechat.url.util.ConvertUtil;
import redis.clients.jedis.exceptions.JedisConnectionException;

import java.io.IOException;

/**
 * Created by P0015475 on 2016/8/10.
 */
public class IndexController extends Controller {

    /**
     * 短链接跳转
     * <p>
     * index方法对应RequestMapping("/")
     *
     * @throws IOException
     */
    public void index() throws IOException {
        String shorturl = getPara();
        Cache cache = Redis.use();
        String longUrl = cache.get(shorturl);
        if (longUrl != null) {
            redirect(longUrl);
        } else {
            if (shorturl == null) {
                setAttr(JsonConst.RESULT, JsonConst.ERROR);
                setAttr(JsonConst.ERROR_MSG, "No parameter.");
                renderJson();
            } else {
                Url first = Url.dao.findFirst("select id,short,`long` from url where short=?", shorturl);
                if (first == null) {
                    setAttr(JsonConst.RESULT, JsonConst.ERROR);
                    setAttr(JsonConst.ERROR_MSG, "The url is not exist.");
                    renderJson();
                } else {
                    longUrl = first.getLong();
                    cache.set(shorturl, longUrl);
                    redirect(longUrl);
                }
            }
        }
    }

    /**
     * 长连接转短链接
     */
    public void toshort() {
        String apikey = getPara(Const.API_KEY);
        String longurl = getPara(Const.LONG_URL);
        String apikey1 = PropKit.get(Const.API_KEY);
        //判断apikey是否正确
        if (apikey1.equals(apikey)) {
            // 从redis中读取shorturl
            String shortUrl = this.checkExist(longurl);
            String prefixUrl = getRequest().getRequestURL().substring(0, getRequest().getRequestURL().length() - 7);
            if (shortUrl != null) {
                // 如果redis中有则直接取redis中的
                setAttr(JsonConst.RESULT, JsonConst.OK);
                setAttr("shorturl", prefixUrl + shortUrl);
                renderJson();
            } else {
                // redis中没有则读取数据库
                Url first = Url.dao.findFirst("select id,short,`long` from url where `long`=?", longurl);
                if (first != null) {
                    shortUrl = first.getShort();
                } else {
                    // 数据库中没有则生成
                    shortUrl = ConvertUtil.longToShort(longurl);
                    new Url().set("short", shortUrl).set("long", longurl).save();
                }
                setAttr(JsonConst.RESULT, JsonConst.OK);
                setAttr("shorturl", prefixUrl + shortUrl);
                Redis.use().set(shortUrl, longurl);
                renderJson();
            }
        } else {
            // apikey不对
            renderJson("what are you nongshalei?");
        }
    }

    private String checkExist(String longurl) {
        Cache cache = Redis.use();
        String[] strings = ConvertUtil.shortUrl(longurl);
        for (String one : strings) {
            String shortUrl;
            try {
                shortUrl = cache.get(one);
            } catch (JedisConnectionException e) {
                return null;
            }
            if (shortUrl != null) {
                return one;
            }
        }
        return null;
    }
}
